PROJECTENGRAM

FILE HANDLING

Topic 4- File Handling

Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Files #◇Data Analysis #◇Searching #◇Structured Data #◇Structured Programming #◇Memory Management


◇Overview

File handling in C allows programs to read from and write to files on disk using the <stdio.h> library and the FILE pointer type.

◇Key Concepts

FILE * pointer represents an open file stream fopen() opens a file; fclose() closes it Modes: "r" (read), "w" (write), "a" (append), "rb"/"wb" (binary) Text I/O: fprintf, fscanf, fgets, fputs Binary I/O: fread, fwrite

◇Details / Theory

Opening and Closing Files

『』
C
FILE *fp = fopen("data.txt", "r");  // Open for reading
if (fp == NULL) {
    printf("Error: Cannot open file.\n");
    return 1;
}

// ... use the file ...

fclose(fp);  // Always close when done

File Modes

ModeDescription
"r"Read (file must exist)
"w"Write (creates/overwrites)
"a"Append (creates if needed)
"r+"Read + Write (file must exist)
"w+"Read + Write (creates/overwrites)
"rb"Read binary
"wb"Write binary

Writing to a Text File

『』
C
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
    fprintf(fp, "Name: %s\n", "Alice");
    fprintf(fp, "Score: %d\n", 95);
    fputs("End of record.\n", fp);
    fclose(fp);
}

Reading from a Text File

『』
C
FILE *fp = fopen("data.txt", "r");
char line[256];

// Read line by line
while (fgets(line, sizeof(line), fp) != NULL) {
    printf("%s", line);
}
fclose(fp);
『』
C
// Structured reading with fscanf
FILE *fp = fopen("students.txt", "r");
char name[50];
int age;
float gpa;

while (fscanf(fp, "%s %d %f", name, &age, &gpa) == 3) {
    printf("%s is %d with GPA %.2f\n", name, age, gpa);
}
fclose(fp);

Binary File I/O

『』
C
typedef struct {
    char name[50];
    int age;
} Student;

// Write binary
FILE *fp = fopen("students.bin", "wb");
Student s = {"Alice", 20};
fwrite(&s, sizeof(Student), 1, fp);
fclose(fp);

// Read binary
fp = fopen("students.bin", "rb");
Student s2;
fread(&s2, sizeof(Student), 1, fp);
printf("%s, %d\n", s2.name, s2.age);
fclose(fp);

File Position Functions

FunctionDescription
ftell(fp)Current position in bytes
fseek(fp, offset, origin)Move to position
rewind(fp)Go back to beginning

Origins for fseek: SEEK_SET (beginning), SEEK_CUR (current), SEEK_END (end).

Checking for End of File

『』
C
while (!feof(fp)) {
    // Read data...
}

Note: Prefer checking the return value of fread/fgets/fscanf rather than using feof() in loop conditions.

◇Common Pitfalls

Not checking if fopen() returns NULL — leads to segfault. Forgetting to fclose() — causes resource leaks and data loss. Using "w" mode when intending to append — overwrites the file. Using feof() as a loop condition — can read one extra iteration. Mixing text and binary modes on Windows (newline translation issues).

◇Summary

TL;DR — File handling uses FILE * with fopen/fclose. Use fprintf/fscanf/fgets for text and fread/fwrite for binary. Always check for NULL on open and close files when done.

Related: ◇Strings — ◇Structs — ◇Recursion — ◇What is an Array Source / Reference:

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

Which library is required for file handling in C?

Q2

What type of pointer is used to represent an open file stream in C?

Q3

What is the result of using the "w" mode with fopen() on an existing file?

Q4

Which function must always be called when you are finished using an open file?

Q5

What does fopen() return if it fails to open a file?

Q6

Which function is specifically used for structured reading of text files, similar to reading from standard input?

Q7

Which functions are primarily used for reading and writing binary files in C?

Q8

What does the ftell(fp) function return?

Q9

Why is using feof() directly as a loop condition generally discouraged?

Q10

What origin constant is used with fseek() to move relative to the beginning of the file?

File Handling | PROJECT ENGRAM